<script lang="ts" setup>
interface DataResource {
  name: string;
  cputotal: number;
  cpuuse: number;
  gpuuse: number;
  gputotal: number;
  diskuse: number;
  disktotal: number;
  memuse: number;
  memtotal: number;
  task: string;
  id: string;
  status: boolean;
  cluster_type: string;
  cluster_region: string;
}

interface NodeResource {
  node_address: string;
  cputotal: number;
  cpuuse: number;
  gpuuse: number;
  gputotal: number;
  diskuse: number;
  disktotal: number;
  memuse: number;
  memtotal: number;
}

interface datafetchClusterMetrics {
  code: number;
  data: {
    cpu_total: number;
    cpu_used: number;
    memory_total: number;
    memory_used: number;
    gpu_total: number;
    gpu_used: number;
    storage_total: number;
    storage_used: number;
    clusters: {
      id: string;
      name: string;
      address: string;
      cluster_type: string; // 假设只有 'cloud' 或 'edge'
      health_status: boolean;
      last_heartbeat: number; // Unix 时间戳
      cpu_total: number;
      cpu_used: number;
      memory_total: number;
      memory_used: number;
      gpu_total: number;
      gpu_used: number;
      storage_total: number;
      storage_used: number;
      task_num: number;
    }[];
  };
}

// 定义响应式数据
const cpuUsage = reactive({ value: 8, maxValue: 12 });
const memoryUsage = reactive({ value: 4858, maxValue: 8176 });
const gpuUsage = reactive({ value: 1, maxValue: 4 });
const diskUsage = reactive({ value: 3494, maxValue: 10405 });
const flag = ref(0); // 初始化 flag
const Data = ref();
const route = useRoute();

const componentKey = ref(0);
const componenttaskKey = ref(0);

// 读取 URL 中的 id 参数
const ClusterId = computed(() => {
  return route.params.slug && route.params.slug.length > 0
    ? (route.params.slug[0] as string)
    : '';
});

const dataresources = ref<DataResource[]>([]);

const noderesources = ref<NodeResource[]>([]);

const clusterresources = ref<DataResource>({
  name: '加载中',
  cputotal: 1,
  cpuuse: 1,
  gpuuse: 6,
  gputotal: 4,
  diskuse: 2,
  disktotal: 4,
  memuse: 4,
  memtotal: 7,
  task: '1',
  id: '10',
  status: true,
  cluster_type: '未定义',
  cluster_region: 'q'
});

const areArraysEqual = (arr1: string[], arr2: string[]): boolean => {
  if (arr1.length !== arr2.length) return false;

  // 转换为 Set 对象进行比较，自动去重且不关心顺序
  const set1 = new Set(arr1);
  const set2 = new Set(arr2);

  // 如果两个 Set 的大小不同，说明不相等
  if (set1.size !== set2.size) return false;

  // 比较每个元素是否在另一个 Set 中存在
  for (let item of set1) {
    if (!set2.has(item)) return false;
  }

  return true;
};

async function fetchClusterMetrics(type: number) {
  const { data } = await useFetch<datafetchClusterMetrics>(
    `/api/v1/cluster/metrics`,
    {
      params: { type } // 动态传递 type 参数
    }
  );
  Data.value = data.value;
  console.log('here', data.value);
  cpuUsage.maxValue = data.value.data.cpu_total;
  cpuUsage.value = data.value.data.cpu_used;
  gpuUsage.value = data.value.data.gpu_used;
  gpuUsage.maxValue = data.value.data.gpu_total;
  memoryUsage.value = data.value.data.memory_used;
  memoryUsage.maxValue = data.value.data.memory_total;
  diskUsage.value = data.value.data.storage_used;
  diskUsage.maxValue = data.value.data.storage_total;
  const newMappedData = data.value.data.clusters.map((cluster: any) => ({
    name: cluster.name,
    cputotal: cluster.cpu_total,
    cpuuse: cluster.cpu_used,
    gpuuse: cluster.gpu_used,
    gputotal: cluster.gpu_total,
    diskuse: cluster.storage_used,
    disktotal: cluster.storage_total,
    memuse: cluster.memory_used,
    memtotal: cluster.memory_total,
    task: cluster.task_num,
    id: cluster.id,
    status: cluster.health_status,
    cluster_type: cluster.cluster_type,
    cluster_region: cluster.cluster_region
  }));
  const newIds = newMappedData.map((item) => item.id);
  const oldIds = dataresources.value.map((item) => item.id);
  if (!areArraysEqual(newIds, oldIds)) {
    // 深度比较
    dataresources.value = newMappedData; // 更新数据
    componentKey.value++; // 仅在 ID 变化时自增
  } else {
    dataresources.value = newMappedData; // ID 相同也更新数据，但不自增 key
  }
}

async function fetchSingleClusterMetrics(clusterId: string) {
  const { data } = await useFetch(`/api/v1/cluster/metrics/${clusterId}`);
  console.log(data.value);
  clusterresources.value.name = data.value.data.name;
  clusterresources.value.cluster_type = data.value.data.cluster_type;
  const newnoderesources = data.value.data.nodes.map((node: any) => ({
    node_address: node.node_address,
    cputotal: node.cpu_total,
    cpuuse: node.cpu_used,
    gpuuse: node.gpu_used,
    gputotal: node.gpu_total,
    diskuse: node.storage_used,
    disktotal: node.storage_total,
    memuse: node.memory_used,
    memtotal: node.memory_total
  }));
  const newIds = newnoderesources.map((item) => item.id);
  const oldIds = noderesources.value.map((item) => item.id);
  if (!areArraysEqual(newIds, oldIds)) {
    // 深度比较
    noderesources.value = newnoderesources; // 更新数据
    //componenttaskKey.value++; // 仅在 ID 变化时自增
  } else {
    noderesources.value = newnoderesources; // ID 相同也更新数据，但不自增 key
  }
}

function toggleFlag() {
  if (flag.value === 1) {
    // 如果 flag 切换为 1，且 selectedInfo 有效，立即调用 fetchSingleClusterMetrics
    fetchSingleClusterMetrics(ClusterId.value as string);
  } else if (flag.value === 0) {
    // 如果切换回全局视图，立即调用 fetchClusterMetrics
    fetchClusterMetrics(0);
  }
}

let intervalId: ReturnType<typeof setInterval>;
watch(ClusterId, (newClusterId) => {
  flag.value = newClusterId ? 1 : 0;
  clusterresources.value.id = ClusterId.value;
});

onBeforeMount(() => {
  if (!route.params.slug || route.params.slug.length === 0) {
    flag.value = 0; // 如果 ClusterId 为空，flag 置 0
    fetchClusterMetrics(0);
  } else {
    flag.value = 1;
    console.log('begfore');
    fetchSingleClusterMetrics(ClusterId.value as string);
  }
});

// 组件挂载时设置定时器
onMounted(() => {
  // 初次加载全局数据
  intervalId = setInterval(() => {
    if (flag.value === 0) {
      fetchClusterMetrics(0); // 当 flag == 0 时更新全局数据
    } else if (flag.value === 1) {
      fetchSingleClusterMetrics(ClusterId.value as string); // 当 flag == 1 且 selectedInfo 有效时更新单个集群数据
    }
  }, 5000); // 每5秒检查一次
});

onUnmounted(() => {
  clearInterval(intervalId);
});
</script>

<template>
  <v-container>
    <v-card variant="text" color="surface-variant">
      <v-label
        v-if="flag == 0"
        class="text-h5"
        style="font-weight: bold; color: black"
      >
        当前集群：未选择<br />请选择集群
      </v-label>

      <v-label v-else class="text-h5" style="font-weight: bold; color: black">
        当前集群：
        <span v-if="clusterresources.cluster_type === 'cloud'">
          云集群{{ clusterresources.name }}
        </span>
        <span v-else-if="clusterresources.cluster_type === 'edge'">
          边集群{{ clusterresources.name }}
        </span>
        <span v-else-if="clusterresources.cluster_type === 'device'">
          端设备{{ clusterresources.name }}
        </span>
        <span v-else> 加载中 {{ clusterresources.name }} </span>
      </v-label>
    </v-card>

    <v-card v-if="flag == 0" class="mb-4" variant="text">
      <SchedulerList :flag="0" :dataresources="dataresources" />
    </v-card>

    <v-card v-else class="mb-4" variant="text">
      <v-card variant="text" color="surface-variant">
        <v-row>
          <v-col class="d-flex justify-end">
            <NuxtLink :to="`/cluster/info`">
              <v-btn color="primary" @click="toggleFlag"> 返回总视图 </v-btn>
            </NuxtLink>
          </v-col>
        </v-row>
      </v-card>
      <SchedulerList :flag="2" :dataresources="noderesources" />
    </v-card>
  </v-container>
</template>
